package slider_verify

import (
	"fmt"
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	"gitee.com/binny_w/go-util"
	"github.com/gin-gonic/gin"
	"math"
	"net/http"
	"strconv"
)

func CheckCode(id, code, ua, ip string) error {
	var err error
	var data map[string]string
	key := fmt.Sprintf("slide_verify:%s", id)
	data, err = core.RedisVerify.HGetAll(key)
	if err != nil {
		return err
	}
	defer func() {
		_, _ = core.RedisVerify.Del(key)
	}()
	if data["Code"] != code || data["UA"] != ua || data["IP"] != ip {
		return fmt.Errorf("wrong code")
	}
	return nil
}

func check(c *gin.Context) {
	var id string
	var x int
	var err error
	var data map[string]string
	if x, err = strconv.Atoi(c.PostForm("x")); err != nil {
		partner.WriteJsonError(c, http.StatusBadRequest, `错误的拼图`)
		return
	}
	id = c.PostForm("id")
	if id == "" {
		partner.WriteJsonError(c, http.StatusBadRequest, `错误的 id`)
		return
	}
	key := fmt.Sprintf("slide_verify:%s", id)
	data, err = core.RedisVerify.HGetAll(key)
	if err != nil {
		partner.WriteJsonError(c, http.StatusBadRequest, `错误的 id`)
		return
	}
	if data["Code"] != "" || data["UA"] != c.Request.UserAgent() || data["IP"] != c.ClientIP() {
		_, _ = core.RedisVerify.Del(key)
		partner.WriteJsonError(c, http.StatusBadRequest, `错误的请求`)
		return
	}
	x1, _ := strconv.Atoi(data["X"])
	if math.Abs(float64(x-x1)) > 5 {
		_, _ = core.RedisVerify.Del(key)
		partner.WriteJsonError(c, http.StatusBadRequest, `错误的拼图`)
		return
	}
	code := util.StrRandom(8, "")
	_, _ = core.RedisVerify.HSet(key, "Code", code)
	partner.WriteJsonSuccess(c, gin.H{
		"code": code,
		"id":   id,
	})
}
